import { utils } from './utils';

const { addSearch, removeSearch } = utils;

export const loginUrlKey = 'sfw4_loginUrl';
export const authTokenKey = 'sfw4_authToken';
export const currentUserKey = 'sfw4_currentUser';
export const currentRenterKey = 'sfw4_currentRenter';

export function addSearchToPathname(
  url: string,
  searchObj: Record<string, any>,
) {
  return addSearch(url, searchObj, true);
}

export function addToken(url: string, toPath?: boolean) {
  const authToken = window.localStorage.getItem(authTokenKey);
  if (!authToken) {
    return url;
  }

  return addSearch(url, { token: authToken }, toPath);
}

export function defaultLogin() {
  return `${window.location.origin}/login`;
}

/**
 * 跳转到登录页面，以下地方使用
 * 1、token 过期后跳转
 * 2、退出登录成功后跳转
 * @param redirect
 */
export function redirectLogin(redirect: boolean = true) {
  const loginUrl = window.localStorage.getItem(loginUrlKey);
  const url = loginUrl || defaultLogin();
  let toUrl = url.toString();
  if (redirect) {
    // toUrl = addSearch(url, { redirect: window.location.origin + window.location.pathname });
    toUrl = addSearch(url, {
      redirect: decodeURIComponent(window.location.href),
    });
  }
  window.location.href = toUrl;
}

export function clearCurrentInfo() {
  globalThis.localStorage.removeItem(authTokenKey);
  globalThis.localStorage.removeItem(currentUserKey);
  globalThis.localStorage.removeItem(currentRenterKey);
}

/**
 * 使用地方：
 * 1、初始化状态时
 * 2、登录应用中处理退出逻辑时
 * @param history
 */
export function tokenHandle(history?: any) {
  // console.log('URL参数', history.location.query);
  // 解析 URL 中的 token
  // const tokenTemp = history.location.query?.token as string;
  const urlParams = new URL(window.location.href).searchParams;
  const tokenTemp = urlParams.get('token');
  console.log(`路径中的 Token: ${tokenTemp}`);
  if (tokenTemp) {
    // Token 变化后清除缓存
    clearCurrentInfo();
    globalThis.localStorage.setItem(authTokenKey, tokenTemp);
    const url = removeSearch(globalThis.location.href, 'token');
    //
    if (history) {
      history.replace(url);
    } else {
      window.history.replaceState({}, '', url);
    }
    return;
  }

  // 不存在 authToken 直接跳登录页面
  const authToken = globalThis.localStorage.getItem(authTokenKey);
  if (!authToken && window.location.pathname.indexOf('/login') === -1) {
    redirectLogin(false);
  }
}

/**
 * 使用位置：
 * 1、登录后跳转到业务系统
 * @param url
 * @param options
 */
export function redirectSfw(
  url: string,
  options?: {
    openNew?: boolean;
    beforeRedirect?: () => void;
  },
) {
  const authToken = globalThis.localStorage.getItem(authTokenKey);
  let toUrl = url;
  if (authToken) {
    toUrl = addSearch(url, { token: authToken });
  }

  if (options?.beforeRedirect) {
    options?.beforeRedirect();
  }

  const openNew = options?.openNew;
  if (openNew) {
    globalThis.open(toUrl, '_blank');
  } else {
    globalThis.location.href = toUrl;
  }
}

export const authentication = {
  clearCurrentInfo,
  tokenHandle,
  redirectLogin,
  redirectSfw,
  addToken,
};
